#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct ListNode {
   int val;
   struct ListNode* next;
}ListNode;
ListNode* BuynewNode()
{
    ListNode* ptr = (ListNode*)malloc(sizeof(struct ListNode));
    return ptr;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode* cur1 = l1, * cur2 = l2;
    struct ListNode* newhead, * newtail;
    newhead = newtail = BuynewNode();
    int num = 0; int x;
    while (cur1 && cur2)
    {
        x = cur1->val + cur2->val + num;
        struct ListNode* ptr = BuynewNode();
        ptr->val = x % 10;
        ptr->next = NULL;
        newtail->next = ptr;
        newtail = ptr;
        if (x >= 10) {
            num = 1;
        }
        else {
            num = 0;
        }
        cur1 = cur1->next;
        cur2 = cur2->next;
    }
    ListNode* cur = cur1;
    if (cur1 == NULL && cur2 != NULL) {
        cur = cur2;
    }
    while (cur)
    {
        x = cur->val + num;
        ListNode* ptr = BuynewNode();
        ptr->val = x % 10;
        ptr->next = NULL;
        newtail->next = ptr;
        newtail = ptr;
        if (x >= 10) {
            num = 1;
        }
        else {
            num = 0;
        }
        cur = cur->next;
    }
    if (num == 1)
    {
        ListNode* ptr = BuynewNode();
        ptr->val = 1;
        ptr->next = NULL;
        newtail->next = ptr;
        newtail = ptr;
    }
    return newhead->next;
}
int main()
{
    ListNode p1, p2, p3, p4;
    p1.val = 3, p2.val = 7, p3.val = 9, p4.val = 2;
    ListNode* l1 = &p1, * l2 = &p3;
    p1.next = &p2; p2.next = NULL;
    p3.next = &p4; p4.next = NULL;
    addTwoNumbers(l1, l2);
    return 0;
}